#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/fs.h>
#include <linux/init.h>
#include <linux/delay.h>
#include <linux/irq.h>
#include <asm/uaccess.h>
#include <asm/irq.h>
#include <asm/io.h>
#include <asm/arch/regs-gpio.h>
#include <asm/hardware.h>

static DECLARE_WAIT_QUEUE_HEAD(button_waitq);

static volatile int ev_press = 0;

static struct class *forth_class;
static struct class_device *forth_class_dev;

static unsigned int keyval;

typedef struct pin_desc{
	unsigned int pin;
	unsigned int keyval;
};

struct pin_desc pins_desc[4] = {
	{S3C2410_GPF0, 0x01},
	{S3C2410_GPF2, 0x02},
	{S3C2410_GPG3, 0x03},
	{S3C2410_GPG11, 0x04},
};

static irqreturn_t button_irq(int irq, void *dev_id)
{
	struct pin_desc *pindesc = (struct pin_desc *)dev_id;
	unsigned int val;

	val = s3c2410_gpio_getpin(pindesc->pin);

	if(val)
	{
		keyval = 0x80 | pindesc->keyval;
	}
	else
	{
		keyval = pindesc->keyval;
	}

	wake_up_interruptible(&button_waitq);
	ev_press = 1;
	
	return IRQ_HANDLED;
}

static int forth_drv_open(struct inode *inode, struct file *file)
{
	request_irq(IRQ_EINT0, button_irq, IRQT_BOTHEDGE, "S2", &pins_desc[0]);
	request_irq(IRQ_EINT2, button_irq, IRQT_BOTHEDGE, "S3", &pins_desc[1]);
	request_irq(IRQ_EINT11, button_irq, IRQT_BOTHEDGE, "S4", &pins_desc[2]);
	request_irq(IRQ_EINT19, button_irq, IRQT_BOTHEDGE, "S5", &pins_desc[3]);

	return 0;
}

static ssize_t forth_drv_read(struct file *file, __user char *buf, size_t count, loff_t *ppos)
{
	if(count != 1)
		return -EINVAL;


	wait_event_interruptible(&button_waitq, ev_press);
	ev_press = 0;
	
	copy_to_user(buf, &keyval, 1);
	return 1;
}

static int forth_drv_close(struct inode *inode, struct file *file)
{
	free_irq(IRQ_EINT0, &pins_desc[0]);
	free_irq(IRQ_EINT2, &pins_desc[1]);
	free_irq(IRQ_EINT11, &pins_desc[2]);
	free_irq(IRQ_EINT19, &pins_desc[3]);
}

static unsigned int forth_drv_poll(struct file *file, poll_table *wait)
{
	unsigned int mask = 0;
	
	poll_wait(file, &button_waitq, wait);

	if(ev_press)
		mask |= POLLIN | POLLRDNORM;

	return mask;
}

static struct file_operations forth_drv_fops = {
	.owner   = THIS_MODULE,
	.open    = forth_drv_open,
	.read    = forth_drv_read,
	.release = forth_drv_close,
	.poll    = forth_drv_poll,
};


int major;
static int forth_drv_init(void)
{
	major = register_chrdev(0, "forth_drv", &forth_drv_fops);

	forth_class = class_create(THIS_MODULE, "forth_drv");

	forth_class_dev = class_device_create(forth_class, NULL, MKDEV(major, 0), NULL, "forth_drv");
	
	return 0;
}

static void forth_drv_exit(void)
{
	unregister_chrdev(major, "forth_drv");
	class_device_unregister(forth_class_dev);
	class_destroy(forth_class);
}

module_init(forth_drv_init);
module_exit(forth_drv_exit);
MODULE_LICENSE("GPL");


